//
//  PlayMusic.m
//  音乐播放器
//
//  Created by dllo on 16/3/19.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "PlayMusic.h"

@interface PlayMusic ()

//@property (nonatomic, retain) NSTimer *timer; //定时器(让它在开始时候开始，暂停时候停止)
@property (nonatomic, assign) CGFloat musicDuration; // 要播放的音乐时长

@property (nonatomic, assign) NSInteger dex; // 播放下标
@property (nonatomic, retain) NSArray *arr;

@property (nonatomic, assign) CGFloat sumtime; //当前播放音乐的总时长

@property (nonatomic, copy) NSString *song; // 当前播放的音乐

@property (nonatomic, assign) BOOL isPlay; // 监测播放状态
@property (nonatomic, assign) CGFloat nowTime; /** 记录当前播放时间 */


//@property (nonatomic, copy) void(^blockPlayTime)(CGFloat); // 该block实现计算播放时间

@end

@implementation PlayMusic

- (instancetype)init {
    self = [super init];
    if (self) {
        
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playNextMushic) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

    }
    return self;
}

/**
 *  音乐播放器单例
 *
 *  @return play本类对象
 */
+ (PlayMusic *)shareMusic {
   
    static PlayMusic *play = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        play = [[PlayMusic alloc] init];
        play.avPlayer = [[AVPlayer alloc] init]; // 初始化系统播放器
        
        play.videoPlay = [[AVPlayer alloc] init];
        play.playerLayer = [[AVPlayerLayer alloc] init];
        
        // 因为每次程序运行时 我只需一次向本地获取用户自定义设置的音量，这样可避免重复向本地获取数据
        
        play.isPlay = NO;
        [play createPlayVolume];
    });
    
    return play;
}

// 枚举set
- (void)setPlayMusicStye:(PlayMusicStye)playMusicStye {
  
    _playMusicStye = playMusicStye;
    
    
}

// bof下一首音乐
- (void)playNextMushic {
    
    switch (_playMusicStye) {
        
        case playMusicStyeSequenceCirculation:{
            _dex++;
        } break;
            
        case playMusicStyeSingle:{
            break;
        } break;
            
        case playMusicStyeRandom:{
            NSInteger a = arc4random() % _arr.count;
            NSLog(@"%ld", a);
            _dex = a;
        } break;
    }
    if (!_arr.count) {
        return;
    }
    if (_dex >= _arr.count) {
        _dex = 0;
    }
    
    [PLAYMUSIC playMusicWithAvUrl:_arr dex:_dex];

    [PLAYMUSIC startPlay];
}

// 下一曲
- (void)downSong {
    switch (_playMusicStye) {
            
        case playMusicStyeSequenceCirculation:{
            _dex++;
        } break;
            
        case playMusicStyeSingle:{
            _dex++;
        } break;
            
        case playMusicStyeRandom:{
            NSInteger a = arc4random() % _arr.count;
            NSLog(@"%ld", a);
            _dex = a;
        } break;
    }
    
    if (_dex >= _arr.count) {
        _dex = 0;
    }
    
    [PLAYMUSIC playMusicWithAvUrl:_arr dex:_dex];
    
    [PLAYMUSIC startPlay];
}

// 上一曲
- (void)upSong {
    
    switch (_playMusicStye) {
            
        case playMusicStyeSequenceCirculation:{
            _dex--;
        } break;
            
        case playMusicStyeSingle:{
            _dex--;
        } break;
            
        case playMusicStyeRandom:{
            NSInteger a = arc4random() % _arr.count;
            NSLog(@"%ld", a);
            _dex = a;
        } break;
    }
    
    if (_dex < 0) {
        _dex = _arr.count - 1;
    }
    
    [PLAYMUSIC playMusicWithAvUrl:_arr dex:_dex];
    
    [PLAYMUSIC startPlay];
}


/**
 *  播放音乐
 *
 *  @param avUrl 音乐加载接口
 */
- (void)playMusicWithAvUrl:(NSArray *)avUrls dex:(NSInteger)dex {
    
    _dex = dex;
    self.arr = avUrls;
   
    WXLSongsModel *songModel = avUrls[dex];
   
    if (songModel.picUrl.length) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeSongs" object:songModel];
    }
    
    NSArray *modelArr = songModel.urlListArr;
    WXLUrlListModel *model = [WXLUrlListModel modelWithDic:nil];
    if (modelArr.count >= 3) {
        model = modelArr[2];
    } else if (modelArr.count == 2) {
        model = modelArr[1];
    } else if (modelArr.count == 1) {
        model = modelArr[0];
    } else {
        [self playNextMushic];
        return;
    }

    self.blockPlayMusic(model, songModel.name, songModel.picUrl, songModel.singerName, songModel.songId, _isPlay);
    
    NSString *avUrl = model.url;

    
    // 确保程序安全运行
    if (!avUrl) {
        [self playNextMushic];
        return;
    }
    
    if (self.avPlayer.currentItem) {
        [self.avPlayer.currentItem removeObserver:self forKeyPath:@"playMusic"];
    }
    
    // 磁盘(磁带：播放地址 放入磁盘)
    self.avPlayItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:avUrl]];
    // 监听音乐播放状态
    [_avPlayItem addObserver:self forKeyPath:@"playMusic" options:NSKeyValueObservingOptionNew context:nil];
    // 添加磁盘到音乐播放器
    [self.avPlayer replaceCurrentItemWithPlayerItem:_avPlayItem];
}

/**
 *  开始播放音乐
 */
- (void)startPlay {
    [self.avPlayer play];
    
    _isPlay = YES;
    self.blockPlayYesOrNo(_isPlay);
    
}

/**
 *  暂停播放音乐
 */
- (void)pausePlay {
    [self.avPlayer pause];
    
    _isPlay = NO;
    self.blockPlayYesOrNo(_isPlay);

}

/**
 *  某一时刻开始播放
 *
 *  @param time 从什么时候开始播放
 */
- (void)seekToTime:(CGFloat)time {
    
    // 某一时间，播放的进度（可以理解为:第一个参数为当前时间 乘 第二个参数每一秒走多少进度 = 进度）
    [self.avPlayer seekToTime:CMTimeMakeWithSeconds(time, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self startPlay];
        }
    }];
}

// 重写volume set方法
- (void)setVolume:(CGFloat)volume {
    self.avPlayer.volume = volume;
    
    NSString *str = [NSString stringWithFormat:@"%f", volume];

    NSDictionary *dic = @{@"volume":str};
    [self saveColorDicToLocal:dic keys:@"volume"];
}

// 重写volume get方法
- (CGFloat)volume {
    return self.avPlayer.volume;
}


// 保存volume (存储当前用户设置音量)
- (void)saveColorDicToLocal:(NSDictionary *)dic keys:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    [defaults setObject:dic forKey:key];
}

// 获取vlume (获取用户上次使用设置音量)
- (NSDictionary *)getColorDicFromLocal:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:key];
    return dic;
}

// 本地是否用户自定义音量
- (BOOL)localHaveColorDic:(NSString *)key {
    
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    
    NSDictionary *dic = [preferences objectForKey:key];
    
    if (dic) {
        return YES;
    }
    return NO;
}

/**
 *  设置播放音量
 *
 *  @return 当前音量值
 */
- (CGFloat)createPlayVolume {
    BOOL isSelfVolume = [self localHaveColorDic:@"volume"];
    /**
     *  如果用户自定义了音量 则启用用户自定义音量 否则为系统默认
     */
    if (isSelfVolume) {
        NSDictionary *dic = [self getColorDicFromLocal:@"volume"];
        CGFloat volume = [dic[@"volume"] floatValue];;
        self.avPlayer.volume = volume;
    } else {
        self.avPlayer.volume = 5;
    }
    
    return self.avPlayer.volume;
}




/**********************************视频播放**********************************/

- (void)playMovieFromUrl:(NSString *)url {
    
    if (!url.length) {
        return;
    }
    if (self.videoPlay.currentItem) {
        [self.videoPlay.currentItem removeObserver:self forKeyPath:@"play"];
    }
    
    self.avPlayItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:url]];
    
    [self.videoPlay replaceCurrentItemWithPlayerItem:_avPlayItem];
    
    self.playerLayer.player = _videoPlay;
    
    // 视频填充模式
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    // 监听播放状态
    [_avPlayItem addObserver:self forKeyPath:@"play" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void)playMV {
    [_videoPlay play];
}

- (void)pauseMV {
    [_videoPlay pause];
}

/**
 *  某一时刻开始播放
 *
 *  @param time 从什么时候开始播放
 */
- (void)seekToTimePalyVideo:(CGFloat)time {
    
    // 某一时间，播放的进度（可以理解为:第一个参数为当前时间 乘 第二个参数每一秒走多少进度 = 进度）
    [self.videoPlay seekToTime:CMTimeMakeWithSeconds(time, self.videoPlay.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self playMV];
        }
    }];
}


@end
